import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests

  timeout: 5000 // request timeout
})

// 请求拦截
service.interceptors.request.use(
  (config) => {
    // console.log('token:', store.getters.token)
    // 非空时 携带token
    const _token = store.getters.token
    if (_token) {
      config.headers.Authorization = `Bearer ${_token}`
    }
    // 携带token
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截
service.interceptors.response.use(
  // 成功
  (response) => {
    // console.log(response)

    const { message, data, success } = response.data
    if (success === false) {
      // 调用接口失败
      Message.error(message)
      // 可以自己通过，Error构造函数弄一个错误
      return Promise.reject(new Error(message))
    } else {
      // 正常返回数据
      return data
    }
  },
  // 失败
  (error) => {
    return Promise.reject(error)
  }
)

export default service
